# encoding: utf-8
class TimeTableImporter

  def initialize(channel_name)
    unless @channel = Channel.find_by_name(channel_name)
      raise StandardError
    end
  end

  def import_from_excel(src_file)
    excel = Excel.new(src_file)

    excel.sheets.each do |sheet|
      (2 .. excel.last_row(sheet)).each do |row_no|
        Program.create(
          :channel_id => @channel.id,
          :day_of_week => day_name_by(sheet),
          :title => str_post_process(excel.cell(row_no, 2, sheet)),
          :pd_name => str_post_process(excel.cell(row_no, 3, sheet)),
          :operator_name  => str_post_process(excel.cell(row_no, 4, sheet)),
          :start_time => sprintf("%s:%s",
            str_post_process(excel.cell(row_no, 5, sheet))[0..1],
            str_post_process(excel.cell(row_no, 6, sheet))[0..1]
          ),
          :end_time => sprintf("%s:%s",
            str_post_process(excel.cell(row_no, 7, sheet))[0..1],
            str_post_process(excel.cell(row_no, 8, sheet))[0..1]
          ),
          :logo_url => str_post_process(excel.cell(row_no, 9, sheet)),
          :logo_position => str_post_process(excel.cell(row_no, 10, sheet)),
          :background_url => str_post_process(excel.cell(row_no, 11, sheet))
        )
      end
    end
  end


  protected

    def str_post_process(v)
      v.to_s.force_encoding("utf-8").strip
    end

    def day_name_by(sheet_name)
      #case sheet_name.split(".").last
      case sheet_name[-3..-1]
      when "mon"
        "monday"
      when "tue"
        "tuesday"
      when "wed"
        "wednesday"
      when "thu"
        "thursday"
      when "fri"
        "friday"
      when "sat"
        "saturday"
      when "sun"
        "sunday"
      end
    end


end
